package rocksea.com.wechat

import io.reactivex.ObservableEmitter
import java.io.ByteArrayOutputStream
import java.net.HttpURLConnection
import java.net.URL

/**
 * Created by Mrw on 2018/2/2.
 *
 */
class HttpImp private constructor()
{
    companion object
    {
        val instance:HttpImp by lazy {
            HttpImp()
        }
        val HOST_NAME = "https://api.avgle.com/v1/videos/1"
    }
    fun requestPhotos(observableEmitter: ObservableEmitter<Any>)
    {
        get(HOST_NAME,null)
    }

    fun get(uri:String,parameterNameMap: Map<String,String>?):String
    {
        val url = URL(uri)
        val httpURLConnection = url.openConnection() as HttpURLConnection
        httpURLConnection.connectTimeout = 5*1000
        httpURLConnection.requestMethod = "GET"
        parameterNameMap.let { it?.map {
            httpURLConnection.addRequestProperty(it.key,it.value)}}
        httpURLConnection.connect()
        if (httpURLConnection.responseCode==200)
        {
            val outStream = ByteArrayOutputStream()
            val data = ByteArray(1024)
            var len = httpURLConnection.inputStream.read(data)
            while (len!=-1)
            {
                outStream.write(data,0,len)
                len = httpURLConnection.inputStream.read(data)
            }
            return (String(outStream.toByteArray()))
        }
        else
        {
            return httpURLConnection.responseMessage
        }
    }
}
